<template>
  <div class="app-container">
    <div class="syl-group">
      <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.native.prevent>
        <el-form-item label="门店名称:" prop="name">
          <el-input
            v-model.trim="queryParams.name"
            placeholder="请输入"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" class="ordinary" style="margin-right: 15px" @click="resetQuery">
            重置
          </el-button>
          <el-button type="primary" size="mini" @click="handleAdd">新建</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="equWristbandList"
        :header-cell-style="{background:'#F3F9FF',color:'#333333',fontWeight: 600}"
      >
        <el-table-column label="序号" align="center" type="index" width="60"/>
        <el-table-column label="门店名称" align="center" prop="storeInfo.name" :show-overflow-tooltip="true" />
        <el-table-column label="门店地址" align="center" prop="storeInfo.adress" :show-overflow-tooltip="true" />
        <el-table-column label="负责人" align="center" prop="storeInfo.contactName" />
        <el-table-column label="联系方式" align="center" prop="storeInfo.contactPhone" />
        <el-table-column label="状态" align="center" prop="storeInfo.status">
          <template slot-scope="scope">
            <span>{{ scope.row.storeInfo.status | capitalize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余产能/最大产能" align="center" prop="storeInfo.capacity" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span
              v-html="getCapacity(scope.row.storeInfo.capacity,scope.row.consumeCapacity)+'/'+scope.row.storeInfo.capacity"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <div class="syl-inner">
              <router-link :to="{path: '/storeList/infoDetails',query:{id:scope.row.storeInfo.id}}">
                <span class="syl-inner-left">查看</span>
              </router-link>
              <span class="syl-inner-right" @click="handleUpdate(scope.row)">编辑</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改门店对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1006px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :lock-scroll="true"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="门店名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入门店名称" :maxlength="10" style="width: 260px" />
            </el-form-item>
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model.trim="form.contactPhone" placeholder="请输入联系方式" :maxlength="11" style="width: 260px" />
            </el-form-item>
            <el-form-item label="所在区域" prop="area">
              <el-cascader
                v-model="selectedOptions"
                style="width: 260px"
                :options="option"
                @change="handleChange"
              />
            </el-form-item>
            <el-form-item label="详细地址" prop="adress">
              <el-input v-model.trim="form.adress" placeholder="请输入详细地址" :maxlength="50" style="width: 260px" />
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="负责人" prop="contactName">
              <el-input v-model.trim="form.contactName" placeholder="请输入负责人" :maxlength="10" style="width: 260px" />
            </el-form-item>
            <el-form-item label="门店产能" prop="capacity">
              <el-input v-model.trim="form.capacity" placeholder="请输入门店产能" :maxlength="50" style="width: 260px" />
            </el-form-item>
            <el-form-item label="门店状态" prop="status">
              <el-switch
                v-model="form.status"
                active-text="营业"
                inactive-text="暂停营业"
                :active-value="1"
                :inactive-value="2"
              />
            </el-form-item>
            <el-form-item label="门店环境" prop="environment">
              <el-upload
                ref="uploadMent"
                :class="[hideUpload===3?'hide':'']"
                :action="upload.url"
                :headers="upload.headers"
                :disabled="upload.isUploading"
                list-type="picture-card"
                :file-list="imageData"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove1"
                :before-upload="beforeAvatarUpload"
                :limit="limitCount"
                :on-success="handleFaceEnvironment"
                :on-exceed="handleAvatarData"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
            <el-form-item label="营业执照" prop="storeslicense">
              <el-upload
                ref="upload"
                :class="[hideList===3?'hide':'']"
                :action="upload.url"
                :headers="upload.headers"
                :disabled="upload.isUploading"
                list-type="picture-card"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
                :limit="limitCount"
                :on-success="handleAvatarSuccess"
                :on-exceed="handleAvatarData"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-divider direction="vertical" />
        <el-button v-preventReClick type="primary" :loading="loadingValue" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--照片弹窗-->
    <el-dialog
      :title="title1"
      :visible.sync="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div style="width: 100%;text-align: center">
        <img style="width: 240px;height: 170px" :src="dialogImageUrl" alt="">
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { regionData } from 'element-china-area-data'
import { addStoreInfo, deleteById, getByDateId, listByName } from '@/api/stream/storeList'
import serverMap from '../../../../config/serverMap'
// 引入image-conversion
import * as imageConversion from 'image-conversion'
export default {
  name: 'Index',
  filters: {
    capitalize: function(value) {
      return value === 1 ? '营业' : '暂停营业'
    }
  },
  data() {
    return {
      // 门店
      hideUpload: null,
      // 业务
      hideList: null,
      // 照片回显
      dialogImageUrl: null,
      // 最大上传数
      limitCount: 3,
      // 遮罩层
      loading: false,
      loadingValue: false,
      // 区域数据
      option: regionData,
      // 区域数据
      selectedOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 门店表格数据
      equWristbandList: [],
      // 状态
      options: [],
      // 弹出层标题
      title: '',
      title1: '',
      // 是否显示弹出层
      open: false,
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        imei: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        adress: undefined,
        areaCode: [],
        areaName: undefined,
        capacity: undefined,
        contactName: undefined,
        contactPhone: undefined,
        creditCode: undefined,
        environmentAttach: [],
        name: undefined,
        status: 2,
        storeCode: undefined,
        storeLicense: [],
        storeLocation: undefined
      },
      // 营业执照数据
      fileList: [],
      // 门店环境数据
      imageData: [],
      // 表单校验
      rules: {
        contactPhone: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          {
            pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
            message: '手机号码有误，请重填',
            trigger: 'blur'
          }
        ],
        capacity: [
          { required: true, message: '产能不能为空', trigger: 'blur' },
          {
            pattern: /^[1-9]{1}[0-9]*$/,
            message: '产能为正整数并且产能不能以0开头',
            trigger: 'blur'
          }
        ],
        adress: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '负责人不能为空', trigger: 'blur' },
          {
            pattern: /^[\u0391-\uFFE5A-Za-z]+$/,
            message: '负责人只能为中文,和字母',
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '门店名称不能为空', trigger: 'blur' },
          {
            pattern: /[\u4e00-\u9fa5]/,
            message: '门店名称只能为中文',
            trigger: 'blur'
          }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: serverMap.base + '/api/sys/files/upload'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 剩余产能 **/
    getCapacity(name, value) {
      return parseInt(name) - parseInt(value)
    },
    /** 查询门店数据列表 **/
    getList() {
      listByName(this.queryParams).then(res => {
        const { total, list } = res.data
        this.total = total
        this.equWristbandList = list
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.$refs.upload.clearFiles()
      this.$refs.uploadMent.clearFiles()
      this.reset()
    },
    // 表单重置
    reset() {
      this.loadingValue = false
      this.fileList = []
      this.imageData = []
      this.selectedOptions = []
      this.form = {
        adress: undefined,
        areaCode: [],
        areaName: undefined,
        capacity: undefined,
        contactName: undefined,
        contactPhone: undefined,
        creditCode: undefined,
        environmentAttach: [],
        name: undefined,
        status: 2,
        storeCode: undefined,
        storeLicense: [],
        storeLocation: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加门店'
      this.$nextTick(() => {
        this.$refs.upload.clearFiles()
        this.$refs.uploadMent.clearFiles()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.storeInfo.id
      this.reset()
      this.title = '编辑门店'
      this.fileList = []
      this.imageData = []
      getByDateId(id).then(res => {
        const { areaCode, environmentAttach, storeLicense } = res.data
        const areaCodeList = areaCode.split(',')
        const environmentAttachList = environmentAttach.split(',')
        const storeLicenseDate = storeLicense.split(',')
        this.selectedOptions = areaCode.split(',')
        this.fileList = storeLicenseDate.map(item => {
          return {
            url: serverMap.baseImg + '/' + item
          }
        })
        this.imageData = environmentAttachList.map(item => {
          return {
            url: serverMap.baseImg + '/' + item
          }
        })
        this.hideUpload = this.imageData.length
        this.hideList = this.fileList.length
        this.open = true
        this.form = res.data
        this.form.environmentAttach = environmentAttachList
        this.form.storeLicense = storeLicenseDate
        this.form.areaCode = areaCodeList
      })
    },
    /** 删除 **/
    handleDelete(row) {
      const id = row.storeInfo.id
      this.$confirm('是否确定删除' + row.name + '<br/>' + '<span style="color: #999999">删除此门店后,将无法查看该门店数据且门店无法工作.</span>', '确认提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(function() {
        return deleteById(id)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      const { environmentAttach, storeLicense } = this.form
      const selectedOptions = this.selectedOptions
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (JSON.stringify(selectedOptions) === '[]') {
            return this.msgInfo('请选择所在区域')
          } else if (typeof selectedOptions === 'string') {
            this.form.areaCode = selectedOptions
          } else {
            this.form.areaCode = selectedOptions.join(',')
          }
          if (JSON.stringify(environmentAttach) === '[]') {
            return this.msgInfo('请至少上传一张门店环境的图片')
          } else if (typeof environmentAttach === 'string') {
            this.form.environmentAttach = environmentAttach
          } else {
            this.form.environmentAttach = environmentAttach.join(',')
          }
          if (JSON.stringify(storeLicense) === '[]') {
            return this.msgInfo('请至少上传一张营业执照的图片')
          } else if (typeof storeLicense === 'string') {
            this.form.storeLicense = storeLicense
          } else {
            this.form.storeLicense = storeLicense.join(',')
          }
          this.form.capacity = parseInt(this.form.capacity)
          this.loadingValue = true
          addStoreInfo(this.form).then(res => {
            if (!res.code) {
              this.open = false
              this.msgSuccess('操作成功')
              this.getList()
            } else {
              this.open = false
            }
          })
        }
      })
      setTimeout(() => {
        this.loadingValue = false
      }, 3000)
    },
    /** 点击文件列表中已上传的文件时的钩子 **/
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      this.title1 = '查看照片'
    },
    // 超出事件
    handleAvatarData() {
      this.msgInfo('图片上传次数最多为3张!')
    },
    // 营业执照上传成功
    handleAvatarSuccess(res, file, fileList) {
      if (res.code === 0) {
        const { data } = res
        this.form.storeLicense.push(data.url)
        this.hideList = fileList.length >= this.limitCount
      }
    },
    /** 营业图片删除 */
    handleRemove(file, fileList) {
      this.form.storeLicense = fileList.map((item) => item.url)
      this.hideList = fileList.length >= this.limitCount
    },
    /** 门店删除 **/
    handleRemove1(file, fileList) {
      this.form.environmentAttach = fileList.map((item) => item.url)
      this.hideUpload = fileList.length >= this.limitCount
    },
    /** 图片上传格式判断 */
    beforeAvatarUpload(file) {
      new Promise((resolve, reject) => {
        const isJPG = file.type.split('/')[1]
        const value = ['jpeg', 'png', 'jpg', 'bmp', 'gif', 'JPEG', 'PNG', 'JPG', 'BMP']
        const name = value.includes(isJPG)
        if (!name) {
          this.msgError('上传图片格式为' + 'jpeg', 'png', 'jpg', 'bmp', 'gif', 'JPEG', 'PNG', 'JPG', 'BMP')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        const _URL = window.URL || window.webkitURL
        // 这里需要计算出图片的长宽
        const img = new Image()
        img.onload = function() {
          file.width = img.width // 获取到width放在了file属性上
          file.height = img.height // 获取到height放在了file属性上
          const valid = img.width > 2000 // 图片宽度大于2000
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (valid || isLt2M) {
            imageConversion.compressAccurately(file, {
              size: 400,
              width: 2000
            }).then(res => { // console.log(33, res)
              resolve(res)
            })
          } else {
            resolve(file)
          }
        } // 需要把图片赋值
        img.src = _URL.createObjectURL(file)
        if (!isLt2M) {
          this.msgError('上传头像图片大小不能超过 2MB,请重新上传!')
        }
        return name && isLt2M
      })
    },
    /** 门店环境上传成功 **/
    handleFaceEnvironment(res, file, fileList) {
      if (res.code === 0) {
        const { data } = res
        this.form.environmentAttach.push(data.url)
        this.hideUpload = fileList.length >= this.limitCount
      }
    },
    /** 省市区 **/
    handleChange(row) {
      this.form.areaCode = row
    }
  }
}
</script>
<style lang="scss" scoped>
.hide {
  /deep/ .el-upload--picture-card {
    display: none;
  }
}

.syl-inner {
  width: 100px;
  margin: auto;
  height: 32px;
  line-height: 32px;
  border-radius: 6px;
  border: 1px solid #5BB0FF;

  .syl-inner-left {
    width: 50%;
    height: 32px;
    float: left;
    text-align: center;
    color: #5BB0FF;
  }

  .syl-inner-right {
    cursor: pointer;
    width: 50%;
    height: 31px;
    float: left;
    background: #5BB0FF;
    color: white;
    border-radius: 0 4px 6px 0;
  }
}

/deep/ .el-divider--vertical {
  height: 2em;
  margin: 0 15px;
}
</style>
